﻿using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Tetris.Interfaces;

namespace Tetris.Blocks
{
    public abstract class AbstractBlock : IBlock
    {
        protected enum RotationAngle {South, East, North, West}

        private Vector2 _position;

        protected Texture2D Texture;
        protected Color Color;
        protected double LastFallen;
        protected RotationAngle CurrentAngle;

        public List<ITile> Tiles { get; set; }
        public int FallDelay { get; set; }
        public bool HasStopped { get; set; }
        public Vector2 Position
        {
            get { return _position; }
            set
            {
                _position = value;
                ReArrangeParts(_position, CurrentAngle);
            }
        }

        protected RotationAngle GetNextRotationAngle()
        {
            switch (CurrentAngle)
            {
                    case RotationAngle.South:
                        return RotationAngle.East;
                    case RotationAngle.East:
                        return RotationAngle.North;
                    case RotationAngle.North:
                        return RotationAngle.West;
                default:return RotationAngle.South;

            }
        }

        public virtual void Rotate()
        {
        }

        protected virtual void ReArrangeParts(Vector2 position, RotationAngle angle)
        {
        }

        public Rectangle[] GetBoundaries()
        {
            Rectangle[] result = new Rectangle[Tiles.Count];
            for (int i = 0; i < Tiles.Count; i++)
            {
                var part = Tiles[i];
                result[i] = new Rectangle((int)part.Position.X - Texture.Width / 2, (int)part.Position.Y - Texture.Height / 2, Texture.Width, Texture.Height);
            }
            return result;
        }

        public void Initialize(IGameManager gameManager)
        {
        }

        public void Update(IGameManager gameManager)
        {
            var now = gameManager.GameTime.TotalGameTime.TotalMilliseconds;
            if (now - LastFallen > FallDelay)
            {
                Position = new Vector2(_position.X, _position.Y + Texture.Height);
                LastFallen = now;
            }
        }

        public void Draw(SpriteBatch spriteBatch, IGameManager gameManager, GameTime gameTime)
        {
            foreach (Tile part in Tiles)
            {
                part.Draw(spriteBatch, gameManager, gameTime);
            }
        }
    }
}
